package com.southwind.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.southwind.common.Cache;
import com.southwind.common.ResultObj;
import com.southwind.entity.Admin;
import com.southwind.entity.User;
import com.southwind.form.UserForm;
import com.southwind.service.AdminService;
import com.southwind.service.UserService;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@RestController
public class RedirectController {

    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @GetMapping("favicon.ico")
    @ResponseBody
    void returnNoFavicon() {

    }

    @RequestMapping("/getCode")
    public String getCode(HttpServletResponse response, HttpSession session) throws IOException {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String code = specCaptcha.text().toLowerCase();
        Cache.map.put("code", code);
        return specCaptcha.toBase64();
    }

    @GetMapping("/login")
    public ResultObj login(UserForm userForm){
        if(userForm.getType() == 4) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", userForm.getLoginname());
            User user = this.userService.getOne(queryWrapper);
            if(user == null) return ResultObj.LOGIN_ERROR_LOGINNAME;
            if(!userForm.getPassword().equals(user.getPassword())) return ResultObj.LOGIN_ERROR_PASSWORD;
            if(!userForm.getCode().equals(Cache.map.get("code").toString())) return ResultObj.LOGIN_ERROR_CODE;
            Cache.map.put("type", userForm.getType());
            Cache.map.put("user", user);
            ResultObj loginSuccess = ResultObj.LOGIN_SUCCESS;
            loginSuccess.setUser(user);
            loginSuccess.setType(userForm.getType());
            return loginSuccess;
        } else {
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            adminQueryWrapper.eq("username", userForm.getLoginname()).eq("type", userForm.getType());
            Admin admin = this.adminService.getOne(adminQueryWrapper);
            if(admin == null) return ResultObj.LOGIN_ERROR_LOGINNAME;
            if(!userForm.getPassword().equals(admin.getPassword())) return ResultObj.LOGIN_ERROR_PASSWORD;
            if(!userForm.getCode().equals(Cache.map.get("code").toString())) return ResultObj.LOGIN_ERROR_CODE;
            Cache.map.put("type", userForm.getType());
            Cache.map.put("user", admin);
            ResultObj loginSuccess = ResultObj.LOGIN_SUCCESS;
            loginSuccess.setAdmin(admin);
            loginSuccess.setType(userForm.getType());
            return loginSuccess;
        }
    }
}
